<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/7/23
 * Time: 15:44
 */

namespace app\admin\controller;


use app\admin\model\GiftUrl;
use app\admin\model\GoldRoomEggPrize;
use app\admin\model\GoldRoomsAgent;
use app\admin\model\GoldRoomsAgentUser;
use app\admin\model\GoldRoomsType;
use app\admin\model\User;
use redis\Redis;
use think\App;

class SwitchBox extends Index
{
    public $redis;
    public function __construct()
    {
        parent::__construct();
        $redis =  new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $redis->auth('susu123');
        $this->redis = $redis;
    }
    //库存一
    public function index()
    {
        return view();
    }
    //库存二
    public function indexTwo()
    {
        return view();
    }
    //库存3
    public function indexThree()
    {
        return view();
    }
    //库存4
    public function indexFour()
    {
        return view();
    }

    public function indexData()
    {
       $goldRoomsType = new GoldRoomsType();
       $data = $goldRoomsType->indexData();
        return json($data);
    }
    //库存礼物添加
    public function switchBoxAdd()
    {
        $goldRoomsType = new GoldRoomsType();
        $res = $goldRoomsType->switchBoxAdd();
        return $res;
    }
    //库存礼物修改
    public function switchBoxEdit()
    {
        $goldRoomsType = new GoldRoomsType();
        $res = $goldRoomsType->switchBoxEdit();
        return $res;
    }
    //礼物信息
    public function loopGiftInfo()
    {
        $goldRoomsType = new GoldRoomsType();
        $res = $goldRoomsType->loopGiftInfo();
        return $res;
    }
    //指定礼物信息（奖池）
    public function getGoldGift()
    {
        $redis = $this->redis;
        $goldRoomsType = new GoldRoomsType();
        $res = $goldRoomsType->getGoldGift($redis);
        return $res;
    }
    //轮次奖品列表
    public function editLoop()
    {
        $redis= $this->redis;
        $mode_type = input('mode_type');
        $gold_id = input('gold_id');
        $custom_loop = json_decode($redis->get('custom_loop_add_'.$mode_type.$gold_id),true);
        $data = [];
        if(!empty($custom_loop)){
            foreach($custom_loop as $k => $v){
                $prize_info = GoldRoomsType::where('id','=',$k)->field('gift_id,gift_type')->find();
                if($prize_info['gift_type'] == 1) {
                    $gift_name = GiftUrl::where('id', '=', $prize_info['gift_id'])->value('gift_name');
                }elseif ($prize_info['gift_type'] == 3){
                    $gift_name = \app\admin\model\Prop::where('id', '=', $prize_info['gift_id'])->value('prop_name');
                }
                $arr['gift_name'] = $gift_name;
                $arr['loop_num'] = $v;
                $arr['prize_id'] = $k;
                $data[] = $arr;
            }
        }
        return view()->assign(['data'=>$data,'gold_id'=>$gold_id,'mode_type'=>$mode_type ]);
    }
    //添加轮次奖品
    public function loopAdd(){
        $redis = $this->redis;
        $gift_id = input('post.gift_id');   //库存
        $loop_num = intval(input('post.loop_num'));
        $gold_id = input('post.gold_id');
        $mode_type = input('post.mode_type');

        $least_time = input('post.least_time');
        $redis->set('least_time'.$mode_type.$gold_id,$least_time);  //保存最小公倍数

        $custom_loop = json_decode($redis->get('custom_loop_add_'.$mode_type.$gold_id),true);
        if(empty($custom_loop)){
            $arr[$gift_id] = $loop_num;
            $re = $redis->set('custom_loop_add_'.$mode_type.$gold_id,json_encode($arr));
        }else{
            $custom_loop[$gift_id] = $loop_num;
            $re = $redis->set('custom_loop_add_'.$mode_type.$gold_id,json_encode($custom_loop));
        }
        dailyLog(['content'=>'添加了模式'.$mode_type.'宝箱'.$gold_id.'的第'.$loop_num.'轮奖品库存ID:'.$gift_id,'type'=>3]);
        if($re) return ['code'=>100,'msg'=>'设置成功'];
        else return ['code'=>-100,'msg'=>'设置失败'];
    }
    //删除轮次奖品
    public function loopDel()
    {
        $redis = $this->redis;
        $gold_id = input('gold_id');
        $mode_type = input('mode_type');
        $prize_id = input('prize_id');
        $custom_loop = json_decode($redis->get('custom_loop_add_'.$mode_type.$gold_id),true);
        dailyLog(['content'=>'删除了模式'.$mode_type.'宝箱'.$gold_id.'第'.$custom_loop[$prize_id].'轮指定的库存ID:'.$prize_id,'type'=>3]);
        unset($custom_loop[$prize_id]);
        $re = $redis->set('custom_loop_add_'.$mode_type.$gold_id,json_encode($custom_loop));
        if($re) return ['code'=>100,'msg'=>'删除成功'];
        else return ['code'=>-100,'msg'=>'删除失败'];
    }
    //清空队列
    public function clearBoxQueue()
    {
        $redis = $this->redis;
        $mode_type = input('mode_type');
        $gold_id  = input('gold_id');
       // if($mode_type == $current_mode)  return ['code'=>-100,'msg'=>'当前模式正在被使用,请切换其他模式再清空'];
        $re = $redis->del('open_box_queue_total_'.$mode_type.$gold_id);
        $res = $redis->del('open_box_queue_'.$mode_type.$gold_id);
        dailyLog(['content'=>'清空了模式'.$mode_type.'宝箱'.$gold_id.'的队列','type'=>3]);
        if($re && $res) return ['code'=>100,'msg'=>'清除并追加成功'];
        else return ['code'=>-100,'msg'=>'清除异常，请及时联系技术'];

    }
    //重置轮次
    public function resetLoop()
    {
        $redis = $this->redis;
        $mode_type = input('mode_type');
        $gold_id  = input('gold_id');
        $re = $redis->set('gold_room_store_loop_add_'.$mode_type.$gold_id,1);
        dailyLog(['content'=>'重置了模式'.$mode_type.'宝箱'.$gold_id.'的轮次','type'=>3]);
        if($re) return ['code'=>100,'msg'=>'重置成功'];
        else return ['code'=>-100,'msg'=>'重置失败'];
    }
    //获取当前模式状态
    public function getLoopStatus()
    {
        $redis = $this->redis;
        $mode_type = input('mode_type');
        $type = $redis->get('mode_type');
        if($mode_type == $type)  $arr['status']  = '正在使用'; //当前模式状态
        else $arr['status']  = '已停用';

        $gold_loop_18 =  $redis->get('gold_room_store_loop_add_'.$mode_type.'18');
        if($gold_loop_18 > 1 ) $arr['gold_loop_18'] = $gold_loop_18 -1;
        else $arr['gold_loop_18'] = 1;   //金宝箱轮次

        if($gold_loop_18 > 3)
            $arr['current_gold_loop_18'] = $gold_loop_18 - 3;
        else
            $arr['current_gold_loop_18'] = 1;

        $gold_loop_19 =  $redis->get('gold_room_store_loop_add_'.$mode_type.'19');
        if($gold_loop_19 > 1 ) $arr['gold_loop_19'] = $gold_loop_19 -1;
        else $arr['gold_loop_19'] = 1;   //至尊宝箱轮次

        if($gold_loop_19 > 3)
            $arr['current_gold_loop_19'] = $gold_loop_19 - 3;
        else
            $arr['current_gold_loop_19'] = 1;


        $arr['default_stock_18'] = $redis->get('open_box_queue_total_'.$mode_type.'18');  //默认库存
        $arr['default_stock_19'] = $redis->get('open_box_queue_total_'.$mode_type.'19');


        $arr['current_stock_18'] = $redis->lLen('open_box_queue_'.$mode_type.'18');  //当前剩余
        $arr['current_stock_19'] = $redis->lLen('open_box_queue_'.$mode_type.'19');

        return $arr;

    }
    //切换模式
    public function changeType()
    {
        $redis = $this->redis;
        $mode_type = input('mode_type');
        $current_mode = $redis->get('mode_type');
        if($current_mode == $mode_type) return ['code'=>-100,'msg'=>'别点了，已经切换成功啦'];
        $res = $redis->set('mode_type',$mode_type);  //模式类型
        //dailyLog(['content'=>'切换了模式'.$mode_type,'type'=>3]);
        if($res) return ['code'=>100,'msg'=>'切换成功'];
        else return ['code'=>-100,'msg'=>'切换失败'];
    }
    //当前模式剩余奖品
//    public function remainBox()
//    {
//        $redis = $this->redis;
//        $gold_id = input('gold_id');
//        $mode_type = input('mode_type');
//        $goldRoomsType = new GoldRoomsType();
//        $loop_count = $goldRoomsType->where(['gold_egg_id'=>$gold_id,'mode_type'=>$mode_type])->sum('default_stock');  //一轮的总数
//        $current_count = $redis->lLen('open_box_queue_'.$mode_type.$gold_id);  //当前剩余
//        $end =  ($current_count - $loop_count *2)-1;  //当前轮次奖品
//        $detail_arr = $redis->lRange('open_box_queue_'.$mode_type.$gold_id,0,$end); //当前轮次礼物信息
//        $result =  [];
//        foreach( $detail_arr as $key => $value ){
//            $value = json_decode($value);
//            $value = (array)$value;
//            if(isset($result[$value['id']])){
//                $result[$value['id']]['num'] += 1;
//            }else{
//                $result[$value['id']]['gift_name'] =  $value['prize_name'];
//                $result[$value['id']]['num'] =  1;
//            }
//        }
//        $sort = array_column($result,'num');
//        array_multisort($sort,SORT_ASC,$result);
//        return view()->assign('data',$result);
//    }
    //指定指定用户

    //宝箱剩余
    public function remainBox()
    {
        $redis = $this->redis;
        $gold_id = input('gold_id');
        $mode_type = input('mode_type');
        $goldRoomsType = new GoldRoomsType();
        $loop_count = $goldRoomsType->where(['gold_egg_id'=>$gold_id,'mode_type'=>$mode_type])->sum('default_stock');  //一轮的总数
        $current_count = $redis->lLen('open_box_queue_'.$mode_type.$gold_id);  //当前库存剩余奖品总数



        $gold_loop =  $redis->get('gold_room_store_loop_add_'.$mode_type.$gold_id);
        if($gold_loop > 1 ) $gold_loop  =  $gold_loop -1;
        else $gold_loop = 1;   //宝箱追加的轮次

        if($gold_loop == 2){
            $total_loop = range($gold_loop-1,$gold_loop);  //总轮次
        }else{
            $total_loop = range($gold_loop-2,$gold_loop); //总轮次
        }

        $one_length = 0;
        $two_length = 0;
        $three_length = 0;
        $one_dec = 0;
        $two_dec = 0;
        $three_dec = 0;
        foreach($total_loop as $k => $v){

            $custom_loop = json_decode($redis->get('custom_loop_add_'.$mode_type.$gold_id),true);  //获取轮次奖品

            if($custom_loop){
                foreach($custom_loop as $kk => $vv){
                    if( ($v % $vv == 0) && ($k == 0) ){
                        $one_length += 1;  //第一轮
                        $one_dec =  $redis->get('gold_room_store_'.$mode_type.$gold_id.$v);
                    }
                    if( ($v % $vv == 0) && ($k == 1) ){
                        $two_length += 1;  //第二轮
                        $two_dec =  $redis->get('gold_room_store_'.$mode_type.$gold_id.$v);
                    }
                    if( ($v % $vv == 0) && ($k == 2) ){
                        $three_length += 1;  //第三轮
                        $three_dec =  $redis->get('gold_room_store_'.$mode_type.$gold_id.$v);
                    }
                }
            }
        }
        $one_dec = $one_dec ? $one_dec : 0;
        $two_dec = $two_dec ? $two_dec : 0;
        $three_dec = $three_dec ? $three_dec : 0;

        if(count($total_loop) == 3){    //有3轮
            $three_sum =  $loop_count + $three_length - $one_dec;  //第三轮总数
            $two_sum =  $loop_count + $two_length - $two_dec;  //第二轮总数
            $one_sum =  $current_count-$three_sum-$two_sum - $three_dec;   //第一轮总数
        }else{       //有两轮
            $two_sum =  $loop_count + $two_length - $two_dec;  //第二轮总数
            $one_sum =  $current_count-$two_sum - $one_dec;   //第一轮总数
        }
        foreach ($total_loop as $k => $v){

            if($k == 0){
                $start = 0; $end = $one_sum - 1;  //第一轮起始位置
            }elseif ($k == 1){
                $start = $one_sum; $end = $one_sum + $two_sum - 1;  //第二轮起始位置
            }else{
                $start = $one_sum+$two_sum; $end = $current_count - 1;  //第三轮起始位置
            }

            $detail_arr = $redis->lRange('open_box_queue_'.$mode_type.$gold_id,$start,$end); //当前轮次礼物信息
            $result =  [];
            foreach( $detail_arr as $key => $value ){
                $value = json_decode($value,true);
            //    $value = (array)$value;
                if(isset($result[$value['id']])){
                    $result[$value['id']]['num'] += 1;
                }else{
                    $result[$value['id']]['id'] =  $value['id'];
                    $result[$value['id']]['gift_name'] =  $value['prize_name'];
                    $result[$value['id']]['num'] =  1;
                }
            }

            $sort = array_column($result,'num');
            array_multisort($sort,SORT_ASC,$result);
            $data[] = $result;
            $loop[] = $v;
        }
        //halt([$three_sum,$two_sum,$one_sum]);
        return view()->assign(['data'=>$data,'loop'=>$loop,'gold_id'=>$gold_id,'mode_type'=>$mode_type]);
    }
    //指定用户
    public function appointUser()
    {
        $redis = $this->redis;
        $gold_id = input('gold_id');
        $mode_type = input('mode_type');
        //当前指定

//       $res =  $redis->hGet('add_looty_list_'.$mode_type.$gold_id,9073);
//        $v = json_decode($res,true);
//        dump($v);
        $loop_now = $redis->hGetAll('add_looty_list_'.$mode_type.$gold_id);
        $loop = [];
      //  re_add_looty_list_118  复制的
        foreach ($loop_now as $k => $v){
            if(!is_array($v)){
                $v = json_decode($v,true);
            }
            foreach($v['buffer'] as $key => $value){
                if($value['status'] == 1){
                    $u_id = User::where('id',$v['user_id'])->value('u_id');
                    $loop[] = [
                        'gold_egg_id'=> $gold_id,
                        'user_id' => $v['user_id'],
                        'u_id' => $u_id,
                        'user_nickname' => $v['user_nickname'],
                        'prize_name' => $value['prize_name'],
                        'loop' => $value['loop'],
                        'loop_now' => $v['loop_now'],
                        'state' => $value['status'],
                        'status' => '抽奖中',
                        'create_time' => $value['create_time']?date("Y-m-d H:i:s",$value['create_time']):'',
                        'update_time' => $value['update_time']?date("Y-m-d H:i:s",$value['update_time']):'',
                        'operator' => $value['operator'],
                    ];
                }
            }
        }
        //指定历史
        $loop_history = $redis->hGetAll('add_looty_list_history_'.$mode_type.$gold_id);
        //re_add_looty_list_history_118 复制的
        foreach ($loop_history as $k => $v){
            if(!is_array($v)){
                $v = json_decode($v,true);
            }
            if($v['buffer']['status'] == 2 || $v['buffer']['status'] == 3){
                $u_id = User::where('id',$v['user_id'])->value('u_id');
                $loop[] = [
                    'gold_egg_id'=> $gold_id,
                    'user_id' => $v['user_id'],
                    'u_id' => $u_id,
                    'user_nickname' => $v['user_nickname'],
                    'prize_name' => $v['buffer']['prize_name'],
                    'loop' => $v['buffer']['loop'],
                    'loop_now' => $v['loop_now'],
                    'state' => $v['buffer']['status'],
                    'status' => $v['buffer']['status'] == 2 ? '已抽中' : '已取消',
                    'create_time' => $v['buffer']['create_time']?date("Y-m-d H:i:s",$v['buffer']['create_time']):'',
                    'update_time' => $v['buffer']['update_time']?date("Y-m-d H:i:s",$v['buffer']['update_time']):'',
                    'operator' => $v['buffer']['operator'],
                ];
            }
        }
        array_multisort(array_column($loop,'state'),SORT_ASC,array_column($loop,'update_time'),SORT_DESC,$loop);
        $prize = json_decode($redis->get('prize_pool'),true);
        $prize_pool = $prize[$gold_id] ? floor($prize[$gold_id]) : 0;
        return view()->assign(['data'=>$loop,'gold_id'=>$gold_id,'mode_type'=>$mode_type,'prize_pool'=>$prize_pool]);
    }
    //指定用户添加
    public function appointUserAdd()
    {
        if(!session('admin_name')){
            return ['code'=>-100,'msg'=>'请重新登录'];
        }
        $redis = $this->redis;
        $u_id = input('post.u_id');
        $total_num = input('post.total_num');
        $id = input('post.id');
        $gold_id =input('post.gold_id');
        $mode_type =input('post.mode_type');
        if(!$mode_type || !$gold_id || !$id || !$total_num){
            return ['code'=>-100,'msg'=>'参数有误'];
        }
        if(count($total_num) != count(array_unique($total_num)))  return ['code'=>-100,'msg'=>'次数不能重复'];

        if(count($total_num) != count($id)) return ['code'=>-100,'msg'=>'缺失必要参数'];

        $userInfo = \app\admin\model\User::where('u_id','=',$u_id)->field('id,nickname')->find();
        if(!$userInfo)  return ['code'=>-100,'msg'=>'用户ID输入错误'];
        $nickname = filterEmoji($userInfo['nickname']);

        $loop_add = json_decode($redis->hGet('add_looty_list_'.$mode_type.$gold_id,$userInfo['id']),true);
        if(!$loop_add){
            $loop_add = [
                'user_id'=>$userInfo['id'],//用户id-
                'user_nickname'=>$nickname,//用户昵称-
                'loop_now' => 1, //当前抽奖次数
                'loop_max' => 1, //最大抽中次数
                'buffer' => [],
            ];
        }
        $total_diamonds = 0;
        for($i = 0;$i<=count($total_num)-1;$i++){
            $goldRoomsType = GoldRoomsType::where('id',$id[$i])->find();
            $gift_type = $goldRoomsType['gift_type'];
            $broadcastMsg = '';
            $sendAttachRoomMsg = '';
            if($gift_type == 1 || $gift_type == 2 ){
                $gift = \app\admin\model\GiftUrl::where('id','=',$goldRoomsType['gift_id'])->find();

                if ($gift['id'] == 31 || $gift['diamonds'] >= 500) {
                    //如果是万能碎片或者奖品价格>=500 发全员广播
                    $broadcastMsg = $goldRoomsType['gift_notice'];
                }else if (isset($gift['gift_notice'])) {
                 //   $sendAttachRoomMsg = $goldRoomsType['gift_notice'];
                }
            }elseif ($gift_type == 3){
                $gift = \app\admin\model\Prop::where('id','=',$goldRoomsType['gift_id'])->field('prop_name as gift_name,prop_pic as gift_url,diamonds')->find();
                $broadcastMsg = $goldRoomsType['gift_notice'];
            }
            $broadcastMsg = $goldRoomsType['gift_notice'];

            $total_diamonds += $gift['diamonds'];

            if( $total_num[$i] > $loop_add['loop_max'] ){
                $loop_add['loop_max'] = $total_num[$i];
            }

            if(!isset($loop_add['buffer'][$total_num[$i]])){
                $loop_add['buffer'][$total_num[$i]] = [
                    'id'=>$id[$i],//库存表id
                    'gift_id'=>$goldRoomsType['gift_id'],//礼物id
                    'gift_type'=>$gift_type,//礼物类型(1,普通礼物,2,万能碎片,3 道具)
                    'prize_name'=>$gift['gift_name'],//奖品名称-
                    'prize_pic'=>$gift['gift_url'],//奖品图片
                    'gift_price'=>$gift['diamonds'],//奖品价值
                    'number'=>1,//奖品数量
                    'sendAttachRoomMsg'=>$sendAttachRoomMsg,//房间广播
                    'broadcastMsg'=>$broadcastMsg,//全服广播
                    'loop'=>$total_num[$i],//指定次数-
                    'status' => 1,//指定状态(1,未启用,2已使用,3已取消)-
                    'create_time' => time() , //指定时间-
                    'update_time' => '',//中奖时间-
                    'operator' => session('admin_name') ,//操作人员-
                ];
            }else{
                return ['code'=>-100,'msg'=>'该次数已经指定'];
            }
        }
        $prize = json_decode($redis->get('prize_pool'),true);
        if($total_diamonds > $prize[$gold_id])  return ['code'=>-100,'msg'=>'价值大于剩余奖池'];

//        if($userInfo['id'] == 2411) {
//            $re = $redis->hExists('agent_looty_list_1' . $gold_id, $userInfo['id']);
//            if ($re) $redis->hDel('agent_looty_list_1' . $gold_id, $userInfo['id']);
//            $res = $redis->hSet('agent_looty_list_1' . $gold_id, $userInfo['id'], json_encode($loop_add));
//        }else{
        $res = $redis->hSet('add_looty_list_'.$mode_type.$gold_id,$userInfo['id'],json_encode($loop_add));
        //        }
        //减去奖池
        $prize[$gold_id] -= $total_diamonds;
        $redis->set('prize_pool',json_encode($prize));
        return ['code'=>100,'msg'=>'设置成功'];
    }
    //取消用户指定
    public function cancelAppointUser()
    {
        $gold_id = input('gold_id');
        $mode_type = input('mode_type');
        $user_id = input('user_id');
        $loop = input('loop');
        $redis = $this->redis;
        $res = $redis->hGet('add_looty_list_'.$mode_type.$gold_id,$user_id);
        if(!is_array($res)){
            $res = json_decode($res,true);
        }
        if($res['buffer'][$loop]['status'] == 2) return ['code'=>-100,'msg'=>'该用户已抽中'];
        if($res['buffer'][$loop]['status'] == 3) return ['code'=>-100,'msg'=>'该用户已取消'];
        if($res['buffer'][$loop]['status'] == 1){
            $res['buffer'][$loop]['status'] = 3;

            $gift_type = $res['buffer'][$loop]['gift_type'];
            if($gift_type == 1 || $gift_type  == 3)
                $diamonds = \app\admin\model\Gift::where('id','eq', $res['buffer'][$loop]['gift_id'])->value('diamonds');
            else
                $diamonds = \app\admin\model\Prop::where('id','eq', $res['buffer'][$loop]['gift_id'])->value('diamonds');
            //加奖池
            $prize = json_decode($redis->get('prize_pool'),true);
            $prize[$gold_id] += $diamonds;
            $redis->set('prize_pool',json_encode($prize));

            $redis->multi();
            $user_draw_history = $res;
            $user_draw_history['buffer'] = $res['buffer'][$loop];
            $rs = $redis->hSet('add_looty_list_history_'.$mode_type.$gold_id,$user_id.time(),json_encode($user_draw_history));

            if(count($res['buffer']) == 1){
                $re = $redis->hdel('add_looty_list_'.$mode_type.$gold_id,$user_id);
            }else{
                unset($res['buffer'][$loop]);
                $re = $redis->hSet('add_looty_list_'.$mode_type.$gold_id,$user_id,json_encode($res));
            }
            $redis->exec();
            if( $re && $rs )  return ['code'=>100,'msg'=>'取消成功'];
            else  return ['code'=>-100,'msg'=>'取消失败'];
        }
    }

    //修改奖池
    public function editPrizePool()
    {
        $redis = $this->redis;
        $prize_pool = input('prize_pool');
        if($prize_pool < 0)  return ['code'=>-100,'msg'=>'不能小于零'];
        $gold_id = input('gold_id');
        $content = input('content');
        $type = input('type');
        // halt(input('post.'));
        if(!trim($content)) return ['code'=>-100,'msg'=>'原因不能为空'];
        if(!in_array($type,[1,2])) return ['code'=>-100,'msg'=>'类型不能为空'];

        $prize = json_decode($redis->get('prize_pool'),true);
        $prize = $prize ? $prize : [];
        $prize[$gold_id] = isset($prize[$gold_id]) ? $prize[$gold_id] : 0;
        if($type == 1){
            $prize[$gold_id] += $prize_pool;
            $flag = '增加';
        }else{
            if($prize_pool > $prize[$gold_id]) return ['code'=>-100,'msg'=>'操作错误'];
            $prize[$gold_id] -= $prize_pool;
            $flag = '减去';
        }

        $re = $redis->set('prize_pool',json_encode($prize));
        if($re){
            dailyLog(['content'=>'宝箱'.$gold_id.'的奖池'.$flag.':'.$prize_pool.';原因:'.$content,'type'=>3]);
            return ['code'=>100,'msg'=>'修改成功'];
        }
        else return ['code'=>-100,'msg'=>'修改失败'];
    }
    //抽奖详情
    public function drawRecord()
    {
        $mode_type = input('mode_type');
        $arr = range(1,4);
        array_unshift($arr,$mode_type);
        $arr = array_unique($arr);
        return view()->assign('mode_type',$arr);
    }

    //奖池比例
    public function prizePool()
    {
        $goldRoomsType = new GoldRoomsType();
        $data = $goldRoomsType->prizePool();
        return view()->assign('data',$data);
    }

    //代理用户
    public function agentUser()
    {
        return view();
    }
    //代理用户数据
    public function agentUserData()
    {
        $agentUser = new GoldRoomsAgentUser();
        $data = $agentUser->agentUserData();
        return json($data);
    }
    //代理用户添加
    public function agentUserAdd()
    {
        $agentUser = new GoldRoomsAgentUser();
        $res = $agentUser->agentUserAdd();
        return $res;
    }
    //修改代理人
    public function agentUserEdit()
    {
        $id = input('id');
        $agentUser = new GoldRoomsAgentUser();
        $agentUserInfo = $agentUser->where(['id'=>$id])->find();
//        $agentUserInfo['u_id'] = User::where('id','eq',$agentUserInfo['user_id'])->value('u_id');
        $agentUserInfo['u_id'] = User::where('user_id','eq',$agentUserInfo['user_id'])->value('u_number');
        return view()->assign('agentUser',$agentUserInfo);
    }
    //修改的数据提交
    public function agentUserEditData()
    {
        $newData = input('post.');
        $agentUser = new GoldRoomsAgentUser();
//        $user_id  = User::where('u_id','eq',$newData['u_id'])->value('id');
        $user_id  = User::where('u_number','eq',$newData['u_id'])->value('user_id');
        if(!$user_id) return ['code'=>-100,'msg'=>'参数有误'];
        $re = $agentUser->where(['id'=>$newData['id']])->find();
        if( ($re['status'] == $newData['status']) && ($re['user_id'] == $user_id)  ) return ['code'=>100,'msg'=>'修改成功'];

        $count = $agentUser->where(['user_id'=>$user_id])->count();
        if($count > 1) return ['code'=>-100,'msg'=>'该用户已存在'];

        $res =  $agentUser->save([
            'status'  => $newData['status'],
            'user_id' => $user_id
        ],['id' => $newData['id']]);

        if($re['status'] != $newData['status']){
            $dec = $newData['status'] == 1 ? '启用了' : '禁用了';
            dailyLog(['content'=>$dec.'代理'.$newData['id'],'type'=>3]);
        }
        if($re['user_id'] != $user_id){
            dailyLog(['content'=>'将代理'.$newData['id'].'的user_id:'.$re['user_id'].'改为'.$user_id,'type'=>3]);
        }

        if($res) return ['code'=>100,'msg'=>'修改成功'];
        else return ['code'=>-100,'msg'=>'修改失败'];
    }
    //代理库存
    public function agentIndex()
    {
        $agentUser = new GoldRoomsAgentUser();
        $data = $agentUser->field('id')->select();
        return view()->assign('data',$data);
    }
    //代理模式数据
    public function agentIndexData()
    {
        $goldRoomAgent = new GoldRoomsAgent();
        $data = $goldRoomAgent->listData();
        return json($data);
    }

    //代理模式添加奖池奖品
    public function agentIndexAdd()
    {
        $goldRoomAgent = new GoldRoomsAgent();
        $res = $goldRoomAgent->agentIndexAdd();
        return $res;
    }

    //代理模式库存修改
    public function agentIndexEdit()
    {
        $goldRoomAgent = new GoldRoomsAgent();
        $res = $goldRoomAgent->agentIndexEdit();
        return $res;
    }

    //指定轮数
    public function agentEditLoop()
    {
        $redis= $this->redis;
        $agent_type = input('agent_type');
        $gold_id = input('gold_id');
        $mode_type = input('mode_type',1);
        $custom_loop = json_decode($redis->get('agent_custom_loop_add_'.$mode_type.$agent_type.$gold_id),true);
        $data = [];
        if(!empty($custom_loop)){
            foreach($custom_loop as $k => $v){
                $prize_info = GoldRoomsAgent::where('id','=',$v)->field('gift_id,gift_type')->find();
                if($prize_info['gift_type'] == 1) {
                    $gift_name = GiftUrl::where('id', '=', $prize_info['gift_id'])->value('gift_name');
                }elseif ($prize_info['gift_type'] == 3){
                    $gift_name = \app\admin\model\Prop::where('id', '=', $prize_info['gift_id'])->value('prop_name');
                }
                $arr['gift_name'] = $gift_name;
                $arr['loop_num'] = $k;
                $arr['prize_id'] = $v;
                $data[] = $arr;
            }
        }
        return view()->assign(['data'=>$data,'agent_type'=>$agent_type,'gold_id'=>$gold_id ]);
    }

    //轮次奖品信息
    public function agentLoopGiftInfo()
    {
        $goldRoomsType = new GoldRoomsAgent();
        $res = $goldRoomsType->agentLoopGiftInfo();
        return $res;
    }

    //轮次奖品添加
    public function agentLoopAdd()
    {
        $redis = $this->redis;
        $gift_id = input('post.gift_id');   //库存
        $loop_num = intval(input('post.loop_num'));
        $gold_id = input('post.gold_id');
        $agent_type = input('post.agent_type');
        $mode_type = input('mode_type',1);
        $custom_loop = json_decode($redis->get('agent_custom_loop_add_'.$mode_type.$agent_type.$gold_id),true);
        if(empty($custom_loop)){
            $arr[$loop_num] = $gift_id;
            $re = $redis->set('agent_custom_loop_add_'.$mode_type.$agent_type.$gold_id,json_encode($arr));
        }else{
            $custom_loop[$loop_num] = $gift_id;
            $re = $redis->set('agent_custom_loop_add_'.$mode_type.$agent_type.$gold_id,json_encode($custom_loop));
        }
        dailyLog(['content'=>'添加了代理'.$agent_type.'宝箱'.$gold_id.'第'.$loop_num.'轮指定的礼物ID:'.$gift_id,'type'=>3]);

        if($re) return ['code'=>100,'msg'=>'设置成功'];
        else return ['code'=>-100,'msg'=>'设置失败'];
    }

    //轮次奖品取消
    public function agentLoopDel()
    {
        $redis = $this->redis;
        $gold_id = input('gold_id');
        $agent_type = input('agent_type');
        $prize_id = input('prize_id');
        $loop_num = input('loop_num');
        $mode_type = input('mode_type',1);
        $custom_loop = json_decode($redis->get('agent_custom_loop_add_'.$mode_type.$agent_type.$gold_id),true);
        dailyLog(['content'=>'删除了代理'.$agent_type.'宝箱'.$gold_id.'第'.$loop_num.'轮指定的礼物ID:'.$custom_loop[$loop_num],'type'=>3]);
        unset($custom_loop[$loop_num]);
        if($custom_loop){
            $re = $redis->set('agent_custom_loop_add_'.$mode_type.$agent_type.$gold_id,json_encode($custom_loop));
        }else{
            $re = $redis->del('agent_custom_loop_add_'.$mode_type.$agent_type.$gold_id);
        }

        if($re) return ['code'=>100,'msg'=>'删除成功'];
        else return ['code'=>-100,'msg'=>'删除失败'];
    }

    //删除所有指定
    public function agentLoopDelAll()
    {
        $redis = $this->redis;
        $agent_type = input('agent_type');
        $gold_id = input('gold_id');
        $mode_type = input('mode_type',1);

        if(!$agent_type || !$gold_id)  return ['code'=>-100,'msg'=>'参数有误'];
        $re = $redis->del('agent_custom_loop_add_'.$mode_type.$agent_type.$gold_id);
        dailyLog(['content'=>'清空了代理'.$agent_type.'宝箱'.$gold_id.'所有指定的轮次礼物','type'=>3]);

        if($re) return ['code'=>100,'msg'=>'删除成功'];
        else return ['code'=>-100,'msg'=>'删除失败'];

    }

    public function agentLoopStatus()
    {
        $redis = $this->redis;
        $agent_type = input('agent_type');
        $mode_type = input('mode_type',1);

        $gold_loop_18 =  $redis->get('agent_store_loop_add_'.$mode_type.$agent_type.'18');
        if($gold_loop_18 > 1 ) $arr['gold_loop_18'] = $gold_loop_18 -1;
        else $arr['gold_loop_18'] = 1;   //金宝箱轮次

        if($gold_loop_18 > 3)
            $arr['current_gold_loop_18'] = $gold_loop_18 - 3;
        else
            $arr['current_gold_loop_18'] = 1;

        $gold_loop_19 =  $redis->get('agent_store_loop_add_'.$mode_type.$agent_type.'19');
        if($gold_loop_19 > 1 ) $arr['gold_loop_19'] = $gold_loop_19 -1;
        else $arr['gold_loop_19'] = 1;   //金宝箱轮次

        if($gold_loop_19 > 3)
            $arr['current_gold_loop_19'] = $gold_loop_19 - 3;
        else
            $arr['current_gold_loop_19'] = 1;

        $arr['default_stock_18'] = $redis->get('agent_queue_total_'.$mode_type.$agent_type.'18');  //默认库存
        $arr['current_stock_18'] = $redis->lLen('agent_queue_'.$mode_type.$agent_type.'18');  //当前剩余

        $arr['default_stock_19'] = $redis->get('agent_queue_total_'.$mode_type.$agent_type.'19');  //默认库存
        $arr['current_stock_19'] = $redis->lLen('agent_queue_'.$mode_type.$agent_type.'19');  //当前剩余

        return $arr;
    }

    //重置轮数
    public function agentResetLoop()
    {
        $redis = $this->redis;
        $agent_type = input('agent_type');
        $gold_id = input('gold_id');
        $mode_type = input('mode_type',1);
        $re = $redis->set('agent_store_loop_add_'.$mode_type.$agent_type.$gold_id,1);
        dailyLog(['content'=>'重置了代理'.$agent_type.'宝箱'.$gold_id.'的轮次','type'=>3]);

        if($re) return ['code'=>100,'msg'=>'重置成功'];
        else return ['code'=>-100,'msg'=>'重置失败'];
    }

    //清空队列
    public function agentClearBoxQueue()
    {
        $redis = $this->redis;
        $agent_type = input('agent_type');
        $gold_id = input('gold_id');
        $mode_type = input('mode_type',1);
        $re = $redis->del('agent_queue_total_'.$mode_type.$agent_type.$gold_id);
        $res = $redis->del('agent_queue_'.$mode_type.$agent_type.$gold_id);
        dailyLog(['content'=>'清空了代理'.$agent_type.'宝箱'.$gold_id.'的队列','type'=>3]);
        if($re && $res) return ['code'=>100,'msg'=>'清除并追加成功'];
        else return ['code'=>-100,'msg'=>'清除异常，请及时联系技术'];
    }

}